import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/util/ImCacheFactory.dart';

import '../../dao/ImMessageDao.dart';
import '../../pojo/Enums.dart';
import '../../pojo/ImPojo.dart';

final class MessageSearchCubit extends Cubit<ContentSearchResultState> {
  MessageSearchCubit() : super(const ContentSearchResultState.init());

  void init() {
    emit(const ContentSearchResultState.success([]));
  }

  Future<void> search(int sessionId, String search) async {
    var messageDao = ImMessageDao();
    List<ImMessage> messages = await messageDao.search(sessionId, search, 500);
    for (var message in messages) {
      message.fromImUser = await ImCacheFactory.getInstance().getImUser(message.fromUserId);
    }
    emit(ContentSearchResultState.success(messages));
  }
}

final class ContentSearchResultState extends Equatable {

  final LoadingState state;
  final List<ImMessage> messages;

  const ContentSearchResultState._({
    this.state = LoadingState.loading,
    this.messages = const <ImMessage>[],
  });

  const ContentSearchResultState.loading() : this._();

  const ContentSearchResultState.init() : this._(state: LoadingState.success);

  const ContentSearchResultState.success(List<ImMessage> messages) : this._(state: LoadingState.success, messages: messages,
  );

  const ContentSearchResultState.failure() : this._(state: LoadingState.failure);

  @override
  List<Object?> get props => [state, messages];

}